import { login, logout } from '@/api/user'
import { getToken, setToken, removeToken, getUserId, setUserId, removeUserId } from '@/utils/auth'

const state = {
  token: getToken(),
  userId: getUserId(),
  call:0,
}
const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },

  SET_USERID: (state, userid) => {
    state.userId = userid
  },
  SET_CALL: (state) => {
    state.call =  state.call+1
  },
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password, code, uuid } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password, code: code, uuid: uuid }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.token)
        commit('SET_USERID', data.id)
        setToken(data.token)
        setUserId(data.id)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  //退出登录
  logout({ commit }) {
    return new Promise((resolve, reject) => {
      logout({ token: state.token }).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_USERID', '')
        removeToken()
        removeUserId()
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },




  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_USERID', '')
      removeToken()
      resolve()
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
